<template>
    <div class="login-wrapper">
        <div class="bg-layer" :style="{ backgroundImage: `url(${bg})` }"></div>
        <div class="login-card">
            <h2>创建账号</h2>
            <el-form ref="formRef" :model="form" :rules="rules" size="large" @keyup.enter="handleRegister">
                <el-form-item prop="username">
                    <el-input v-model="form.username" placeholder="请输入账号" :prefix-icon="User" clearable />
                </el-form-item>
                <el-form-item prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" :prefix-icon="Message" clearable />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="form.password" placeholder="请输入密码" :prefix-icon="Lock" show-password clearable />
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" placeholder="请再次输入密码" :prefix-icon="Lock" show-password
                        clearable />
                </el-form-item>
                <el-button type="primary" size="large" style="width: 100%" :loading="loading"
                    @click="handleRegister">注册</el-button>
            </el-form>
            <div class="switch">
                <el-link type="primary" underline="never" @click="goLogin">已有账号？去登录</el-link>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { User, Lock, Message } from '@element-plus/icons-vue'
import bg from '@/assets/images/aa.svg'
import { register } from '@/api/login'

const router = useRouter()
const formRef = ref()
const loading = ref(false)
const form = reactive({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
})
const rules = {
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 5, max:10, message: '用户名的长度最低5位，最长10位', trigger: 'blur' },
        ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const emailReg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
                if (!emailReg.test(value)) {
                    callback(new Error('邮箱地址不正确'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 18, message: '密码长度需为6-18位', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/.test(value)) {
                    callback(new Error('密码需包含字母和数字'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ]
}

function handleRegister() {
    formRef.value.validate(async valid => {
        if (!valid) return
        loading.value = true
        try {
            await register({
                username: form.username,
                password: form.password,
                email: form.email
            })
            ElMessage.success('注册成功！正在跳转到登录页面...')
            
            // 将注册的用户名存储到localStorage，供登录页面使用
            localStorage.setItem('registeredUsername', form.username)
            
            // 延迟跳转，让用户看到成功消息
            setTimeout(() => {
                router.push('/login')
            }, 1500)
        } catch (e) {
            ElMessage.error(e?.message || '注册失败')
        } finally {
            loading.value = false
        }
    })
}
function goLogin() {
    router.push('/login')
}
</script>

<style scoped>
.login-wrapper {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}

.bg-layer {
    background-image: url('@/assets/images/aa.svg');
    position: absolute;
    top: 0;
    left: 0;
    width: 110%;
    height: 110%;
    background-size: cover;
    background-position: center;
    animation: float 20s ease-in-out infinite;
}

@keyframes float {
    0% {
        transform: translateY(0) scale(1);
    }

    50% {
        transform: translateY(-5%) scale(1.05);
    }

    100% {
        transform: translateY(0) scale(1);
    }
}

.login-card {
    position: relative;
    width: 400px;
    max-width: 90%;
    padding: 48px 32px;
    border-radius: 16px;
    backdrop-filter: blur(8px);
    background: rgba(255, 255, 255, 0.75);
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.2);
}

.login-card h2 {
    text-align: center;
    margin: 0 0 32px;
    font-size: 28px;
    color: #333;
}

.switch {
    text-align: center;
    margin-top: 16px;
}
</style>